Skip to content

Latest commit

 

History

History
71 lines (57 loc) · 1.92 KB

File metadata and controls

71 lines (57 loc) · 1.92 KB

2384. Largest Palindromic Number

You are given a string num consisting of digits only.

Return the largest palindromic integer (in the form of a string) that can be formed using digits taken fromnum. It should not contain leading zeroes.

Notes:

  • You do not need to use all the digits of num, but you must use at least one digit.
  • The digits can be reordered.

Example 1:

Input: num = "444947137" Output: "7449447" Explanation: Use the digits "4449477" from "444947137" to form the palindromic integer "7449447". It can be shown that "7449447" is the largest palindromic integer that can be formed. 

Example 2:

Input: num = "00009" Output: "9" Explanation: It can be shown that "9" is the largest palindromic integer that can be formed. Note that the integer returned should not contain leading zeroes. 

Constraints:

  • 1 <= num.length <= 105
  • num consists of digits.

Solutions (Rust)

1. Solution

implSolution{pubfnlargest_palindromic(num:String) -> String{letmut count = [0;10];letmut digits = vec![];for digit in num.bytes(){ count[(digit - b'0')asusize] += 1;}for i in(0..=9).rev(){while count[i] > 1{ count[i] -= 2; digits.push(i asu8 + b'0');}}if*digits.get(0).unwrap_or(&b'1') == b'0'{ digits.clear();}letmut digits_rev = digits.clone(); digits_rev.reverse();ifletSome(i) = (0..=9).rev().find(|&i| count[i] > 0){ digits.push(i asu8 + b'0');} digits.append(&mut digits_rev);if digits.is_empty(){ digits.push(b'0');}String::from_utf8(digits).unwrap()}}
close